import React, { Component } from 'react';
import { bindMethods } from '../untils';
import { Home } from '../components';

export default class HomeContainer extends Component {
  constructor() {
    super();
    this.state = {
      lists: [],
      id: 0,
      isEdit: false,
      activeCate: 0,
      sliderShow: false,
    };
    this.isCheckAll = false;

    // 绑定方法
    bindMethods(this, [
      'handleCheckedItem',
      'handleCheckedAll',
      'handleDelete',
      'handleFilter',
      'handleEditOperation',
      'handleActiveType',
      'handleSliderWrap',
    ]);
  }
  componentWillMount() {
    if (!localStorage.getItem('noteData')) {
      localStorage.setItem('noteData', JSON.stringify([]));
    }

    this.setState({
      lists: JSON.parse(localStorage.getItem('noteData')),
      id: +localStorage.getItem('id'),
    });
  }
  // 删除
  handleDelete() {
    const newList = this.state.lists.filter(item => !item.checked);
    this.setState({
      lists: newList,
      isEdit: !this.state.isEdit,
    }, () => {
      localStorage.setItem('noteData', JSON.stringify(this.state.lists));
    });
  }
  // 单选
  handleCheckedItem(index) {
    this.setState({
      lists: [
        ...this.state.lists.slice(0, index),
        Object.assign(this.state.lists[index], {
          checked: !this.state.lists[index].checked,
        }),
        ...this.state.lists.slice(index + 1),
      ],
    });
  }
  // 全选
  handleCheckedAll() {
    this.isCheckAll = this.state.lists.some(item => !item.checked);
    this.setState({
      lists: this.state.lists.map(item => (
        Object.assign(item, {
          checked: this.isCheckAll,
        })
      )),
    });
  }
  // 筛选
  handleFilter(type) {
    const lists = JSON.parse(localStorage.getItem('noteData'));
    this.setState({
      lists: type === 0 ? lists : lists.filter(item => item.filter === type),
    });
  }
  // 单项选取
  handleEditOperation() {
    this.setState({
      isEdit: !this.state.isEdit,
    });
  }
  // 切换侧边栏
  handleSliderWrap(bool) {
    this.setState({
      sliderShow: bool,
    });
  }
  // 类型选择切换
  handleActiveType(index) {
    this.setState({
      activeCate: index,
    });
  }
  render() {
    return (
      <Home
        {...this}
        {...this.state}
      />
    );
  }
}
